﻿using SpeakToMe.Core;
using SpeakToMe.Core.Enums;
using SpeakToMe.Core.Interfaces;
using SpeakToMe.Speech.Questions;
using SpeakToMe.Speech.Tokens;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;


namespace SpeakToMe.Speech
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class CommandProcessor
    {
        [Import]
        private QuestionManager QuestionManager { get; set; }

        // ******** This is the entry point for requesting the processor analyse and respond to a command *******//
        public void ProcessCommand(string command, int userId,
            ConversationType mode,
            string address,
            ISmartHomeServiceCallback callback)
        {
            string localCommand = command.ToLower().Replace("'", "");
            var context = ServiceLocator.GetInstance<ConversationContext>();
            context.Init(userId, mode, address, callback);
            var tokenManager = ServiceLocator.GetInstance<TokenManager>();
            var buckets = tokenManager.TokenizeInput(localCommand, userId);
            context.LogRequest(command, buckets);

            //before we check the tokens against rules, let's see if we match any questions
            Question question = null;
            List<Token> tokens = new List<Token>();

            this.QuestionManager.CheckForMatchingQuestion(buckets, mode, userId,
                address, ref question, ref tokens);

            if (question != null)
            {
                question.ExecuteIfAnswered.Invoke(context,
                    question.State, tokens);

                this.QuestionManager.RemoveQuestion(question);

                return;
            }

            RuleMethod ruleMethod = RuleManager.LocateMatchingRule(buckets, context);

            if (ruleMethod != null)
            {
                ruleMethod.Rule.Invoke(null, ruleMethod.PassIns);
            }
            else
            {
                context.Say("I didn't understand your request", null);
            }
        }
    }
}